package com.mijie.util;

import java.util.UUID;

import javapns.back.PushNotificationManager;
import javapns.back.SSLConnectionHelper;
import javapns.data.Device;
import javapns.data.PayLoad;

import org.apache.log4j.Logger;


public class IPhonePushUtil {

	private static Logger logger = Logger.getLogger(IPhonePushUtil.class);
	
	public static void main(String[] args){
		String certificatePath  = "/Users/zhengzb/dev/workspace/mijie-common/src/com/mijie/util/Homing_Dev_Push.p12";//导出的证书
		String certificatePassword = "mijie";//此处注意导出的证书密码不能为空因为空密码会报错
		String deviceToken = "ecdfe13a 29316dfd 75aed806 de8bd25c 12f31af1 b8589c64 c492c803 d8571ee7";//iphone手机获取的token
		pushNotify(deviceToken,certificatePath,certificatePassword,"Hello iPhone",-1,true);
	}
	
	/***********************************************************************************************************
	 * 测试的服务器地址：gateway.sandbox.push.apple.com /端口2195 产品推送服务器地址：gateway.push.apple.com / 2195
	 **********************************************************************************************************/
	private static String testHost = "gateway.sandbox.push.apple.com";
	private static String host = "gateway.push.apple.com";
	private static int port = 2195;
	public static boolean pushNotify(String deviceToken,String certificatePath,String certificatePassword,String alert,int badge,boolean test)
	{
		boolean succ = false;
		try{
			PayLoad payLoad = new PayLoad();
			payLoad.addAlert(alert.length()>64?alert.substring(0,64):alert);//push的内容
			if(badge>0)
				payLoad.addBadge(badge);//图标小红圈的数值
			payLoad.addSound("default");//铃音
			PushNotificationManager pushManager = PushNotificationManager.getInstance();
			String tmpName = UUID.randomUUID().toString();
			pushManager.addDevice(tmpName, deviceToken);
			//Connect to APNs
			pushManager.initializeConnection(test?testHost:host, port, certificatePath, certificatePassword, SSLConnectionHelper.KEYSTORE_TYPE_PKCS12);
			//Send Push
			Device client = pushManager.getDevice(tmpName);
			pushManager.sendNotification(client, payLoad);
			pushManager.stopConnection();
			pushManager.removeDevice(tmpName);
			succ = true;
		}catch (Exception e){
			logger.error(e.getMessage(), e);
		}
		return succ;
	}
}
